


#include "qe_bitstream.h"



static inline qe_u32 bit_extract(qe_bitstream *s)
{
    int byte_offs = s->offs / 8;
    int bit_offs = 7 - (s->offs % 8);
    char byte = s->buf[byte_offs];
    int bit = (byte >> bit_offs) & 0x01;
    s->offs++;
    return bit;
}

void qe_bitstream_skip_bits(qe_bitstream *s, int n)
{
    if (!s)
        return;
    s->offs += n;
}

qe_u32 qe_bitstream_get_bits(qe_bitstream *s, int n)
{
    int i;
    qe_u32 v = 0;

    if (n > QE_BITS_PER_LONG) {
        return -1;
    }

    for (i=0; i<n; i++) {
        int bit = bit_extract(s);
        v = (v << 1) | bit;
    }

    return v;
}

qe_u32 qe_bitstream_test_bits(qe_bitstream *s, int n)
{
    qe_u32 val = 0;
    for (int i=0; i<n; i++) {
        int bit = bit_extract(s);
        val = (val << 1) | bit;
    }
    qe_bitstream_skip_bits(s, -n);
    return val;
}

void qe_bitstream_init(qe_bitstream *s, qe_const_ptr *buf, qe_size size)
{
    if (!s || !buf || !size)
        return;
    s->buf  = (const qe_u8 *)buf;
    s->end  = s->buf + size;
    s->offs = 0;
}